package com.crack.test2;

import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.text.Layout;
import android.text.SpannableStringBuilder;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;

import com.crack.spansframe.extra.IAsync;
import com.crack.spansframe.SpanSolve;
import com.crack.test.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Main2Activity extends BaseActivity implements AbsListView.OnScrollListener {

    static String url1 = "http://bbs.ngacn.cc/read.php?tid=9197697";
    static String url2 = "http://bbs.bigccq.cn/read.php?tid=9213548";

    int screenHeight;
    static String PREFIX = "http://img.nga.cn/attachments/";
    List<String> mContents = new ArrayList<>(20);
    List<SpannableStringBuilder> mSpans = new ArrayList<>(20);
    ListView mListView;
    boolean enable = true;
    int startIndex = -1;
    int endIndex = -1;
    int scrollState = -1;

    HandlerThread thread = new HandlerThread("work");
    Handler mMainHandler = new Handler(Looper.getMainLooper());
    Handler mWorkHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!thread.isAlive()) {
            thread.start();
        }
        mWorkHandler = new Handler(thread.getLooper());
        setContentView(R.layout.activity_main2);
        screenHeight = getResources().getDisplayMetrics().heightPixels;
        mListView = (ListView) findViewById(R.id.list);
        mListView.setOnScrollListener(this);
        SpanSolve.injectContext(this);
        readData();
        mListView.setAdapter(new SpanAdapter(mListView, mSpans));
    }

    private void readData() {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("test2")));
            String jsonString = reader.readLine();
            reader.close();
            pauseJson(jsonString);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void pauseJson(String jsonString) {
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            for (int i = 0; i < 20; i++) {
                String key = String.valueOf(i);
                JSONObject object = jsonObject.getJSONObject(key);
                String content = object.getString("content");
                content = content.replaceAll("(\\[img\\])\\./(.*?)(\\[/img\\])", "$1" + PREFIX + "$2$3");
                mContents.add(content);
                SpanSolve spanSolve = new SpanSolve(content);
                SpannableStringBuilder sp = spanSolve.resolve();
                mSpans.add(sp);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        this.scrollState = scrollState;
        switch (scrollState) {
            case SCROLL_STATE_FLING:
                enable = false;
                break;
            case SCROLL_STATE_TOUCH_SCROLL:

                break;
            case SCROLL_STATE_IDLE:
                for (int i = 0; i <= last - first; i++) {
                    scrollComplete(view, (TextView) view.getChildAt(i));
                }
                break;
        }
    }

    private void scrollComplete(AbsListView listView, TextView view) {
        int top = view.getTop() >= 0 ? 0 : -view.getTop();
        int bottom = Math.min(listView.getHeight(), view.getBottom()) - view.getTop();
//        top -= view.getPaddingTop();
//        bottom -= view.getPaddingTop();
        Layout layout = view.getLayout();
        int startLine = layout.getLineForVertical(top);
        int endLine = layout.getLineForVertical(bottom);
        int start = layout.getOffsetForHorizontal(startLine, 0);
        int end = layout.getOffsetForHorizontal(endLine, layout.getLineWidth(endLine));
        int pos = listView.getPositionForView(view);
        SpannableStringBuilder sp = mSpans.get(pos);
        IAsync[] iAsyncs = sp.getSpans(start, end, IAsync.class);
        for (final IAsync iAsync : iAsyncs) {
            mWorkHandler.post(new Runnable() {
                @Override
                public void run() {
                    final Object object = iAsync.get();
                    mMainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            iAsync.set(object);
                        }
                    });
                }
            });
        }
    }

    TextView topView;
    TextView bottomView;
    int first;
    int last;

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//            setStartIndex(firstVisibleItem);
//            setEndIndex(firstVisibleItem + visibleItemCount);
//            notifyScrollChange(firstVisibleItem);
//            notifyScrollChange(firstVisibleItem + visibleItemCount);
        topView = (TextView) view.getChildAt(0);
        bottomView = (TextView) view.getChildAt(visibleItemCount - 1);
        first = firstVisibleItem;
        last = firstVisibleItem + visibleItemCount - 1;
    }


    private void notifyScrollChange(int index) {

    }

    public void setStartIndex(int startIndex) {
        if (startIndex > this.startIndex) {
            release(this.startIndex);
        }
        if (startIndex < this.startIndex) {
            load(startIndex);
        }
        this.startIndex = startIndex;
    }

    public void setEndIndex(int endIndex) {
        if (endIndex > this.endIndex) {
            load(endIndex);
        }
        if (endIndex < this.endIndex) {
            release(this.endIndex);
        }
        this.endIndex = endIndex;
    }

    private void release(int startIndex) {

    }

    private void load(int startIndex) {

    }


}


























